<script>
import { getToken, getUserInfo } from './common/auth';
import { DEFAULT_MSG_PACKAGE_PREFIX, MESSAGE,NOTIFY_MSG, isEmpty } from './common/xiaofei-im/xiaofei-im-utils';
import './common/xiaofei-im/DefaultMsg_pb';
export default {
  onLaunch: function () {
    let that = this;
    uni.$on("setVuexUserInfo", function (data) {
      that.setVuexUserInfo(data.user, data.isLoginPage);
    });
    uni.$on("init", function () {
      console.log("init")
    });
    uni.$on("unsignedHandler", function() {
      console.log("unsignedHandler");
    });
    if(!isEmpty(getToken())){
      this.$fim.msgCallback = this.msgCallback;
    }
  },
  onShow: function () {},
  onHide: function () {},
  methods: {
    // 断线重连或用户刷新浏览器之后的初始化
    init() {
      let userId = null;
      if (this.$u.test.isEmpty(this.$store.getters.id)) {
        // 如果本地存在用户信息则把当前用户和socket绑定在一起，不存在则登录之后再绑定
        let user = getUserInfo();
        if (user != null && !this.$u.test.isEmpty(user.id)) {
          userId = user.id;
        }
      } else {
        userId = this.$store.getters.id;
      }
      if (!this.$u.test.isEmpty(userId)) {
        // 获取断线重连未接收的消息
        this.unsignedHandler(userId);
      }
    },
    // websocket函数回调：返回监听的数据
    msgCallback(msgKey, msg){
      if( msgKey === MESSAGE){
        const type = msg.type
        if(type === DEFAULT_MSG_PACKAGE_PREFIX.TransportMsg.MsgType.PRIVATE){
          uni.$emit("receivePrivateMsg", msg.msg)
        }else if(type === DEFAULT_MSG_PACKAGE_PREFIX.TransportMsg.MsgType.GROUP){
          uni.$emit("receiveGroupMsg",  msg.msg)
        }else if (type === DEFAULT_MSG_PACKAGE_PREFIX.TransportMsg.MsgType.OTHER) {

        }
      }else if(msgKey === NOTIFY_MSG){
        uni.$emit("receiveNotifyMsg", msg);
      }
      console.log("msgKey=", msgKey, "msg=",msg); 
    },
    setVuexUserInfo(user, isLoginPage) {
      let isEmptyStr = this.$u.test.isEmpty(this.$store.getters.id);
      if (!isLoginPage && isEmptyStr) {
        user = getUserInfo();
        // 如果缓存为空则跳转到登录页面
        if (user == null && !isLoginPage) {
          let pages = getCurrentPages();
          if (pages.pop().route !== "pages/login/login") {
            this.$u.route({
              type: "reLaunch",
              url: "/pages/login/login",
            });
          }
        }
      }
      if (isLoginPage || isEmptyStr) {
        if (user != null) {
          this.$store.commit("SET_ROLE", user.role);
          this.$store.commit("SET_ID", user.id);
          this.$store.commit("SET_NAME", user.name);
          this.$store.commit("SET_NUM", user.num);
          this.$store.commit("SET_EMAIL", user.email);
          this.$store.commit("SET_AVATAR", user.avatar);
        }
      }
    },
  }
};
</script>

<style lang="scss">
/*每个页面公共css */
@import "static/css/iconfont.css";
@import "uview-ui/index.scss";
</style>
